<?php

namespace api\web\controller;

use api\web\model\AddressModel;
use api\web\model\UserModel;
use api\web\validate\AddressValidate;
use api\web\validate\UserValidate;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;

class UserController extends RestBaseController
{
    //注册
    public function register()
    {
        // 获取请求数据
        $data = Request::post();

        // 验证数据
        $validate = new UserValidate();
        if (!$validate->scene('register')->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        // 检查手机号是否已存在
        if (UserModel::where('mobile', $data['mobile'])->find()) {
            return json(['status' => 'error', 'message' => '手机号已被注册']);
        }

        // 验证短信验证码
        if (!$this->checkSmsCode($data['mobile'], $data['code'], true)) {
            return json(['status' => 'error', 'message' => '验证码错误或已过期']);
        }

        // 创建用户
        try {
            $user = UserModel::create($data);
            // 生成 token
            $token = signToken($user->id, $user->mobile);
            return json(['status' => 'success', 'data' => $user->toArray(), 'token' => $token]);
        } catch (\Exception $e) {
            return json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }
//登录
    public function login()
    {
        $data = Request::post();

        // 验证数据
        $validate = new UserValidate();
        if (!$validate->scene('login')->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        // 获取用户信息
        $user = UserModel::where('mobile', $data['mobile'])->find();
        if (!$user) {
            return json(['status' => 'error', 'message' => '账号不存在']);
        }

        // 验证验证码
        if (!$this->checkSmsCode($data['mobile'], $data['code'], true)) {
            return json(['status' => 'error', 'message' => '验证码错误或已过期']);
        }

        // 生成 token
        $token = $this->signToken($user->id, $user->mobile);
        return json(['status' => 'success', 'data' => ['token' => $token], 'message' => '登录成功']);
    }
    public function signToken($userId, $mobile)
    {
        $data = [
            // 签发人
            'iss' => request()->domain(),
            // 签发时间
            'iat' => time(),
            // 自定义数据
            'data' => [
                'user_id' => $userId,
                'mobile' => $mobile,
            ]
        ];
        $key = config('app.jwt_key');
        $token = \Firebase\JWT\JWT::encode($data, $key, 'HS256');
        return $token;
    }
//发送验证码
    public function sendSms()
    {
        $mobile = Request::post('mobile');

        // 验证数据
        $validate = new UserValidate();
        if (!$validate->scene('sendsms')->check(['mobile' => $mobile])) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        // 生成验证码
        $code = mt_rand(1000, 9999);

        // 将验证码存储到数据库，有效期5分钟
        Db::name('sms_code_log')->insert([
            'mobile' => $mobile,
            'code' => $code,
            'send_time' => time()
        ]);

        // 发送短信
        $config = new Config([
            "accessKeyId" => 'LTAI5tCEJGR35YytCEk4eKHb',
            "accessKeySecret" =>'FccTZVR3FhR7Vrix8OttNVtsTn9gqo'
        ]);
        $config->endpoint = "dysmsapi.aliyuncs.com";
        $client = new Dysmsapi($config);

        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $mobile,
            "signName" => "阿里云短信测试",
            "templateCode" => "SMS_154950909",
            "templateParam" => json_encode(["code" => $code])
        ]);

        try {
            $runtimeOptions = new RuntimeOptions([
                "verify" => "D:\phpstudy_pro\Extensions\php\php8.0.2nts\extras\ssl\cacert-2024-03-11.pem" // 修改为你实际的 CA 证书文件路径
            ]);
            $client->sendSmsWithOptions($sendSmsRequest, $runtimeOptions);
            return json(['status' => 'success', 'message' => '短信发送成功']);
        } catch (\Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            return json(['status' => 'error', 'message' => $error->getMessage()]);
        }
    }
//检查验证码
    private function checkSmsCode($mobile, $code, $deleteAfterCheck = false)
    {
        // 检查验证码是否正确且未过期
        $smsCodeLog = Db::name('sms_code_log')->where('mobile', $mobile)->order('send_time', 'desc')->find();
        if ($smsCodeLog && $smsCodeLog['code'] == $code && (time() - $smsCodeLog['send_time']) <= 300) {
            if ($deleteAfterCheck) {
                Db::name('sms_code_log')->where('id', $smsCodeLog['id'])->delete();
            }
            return true;
        }
        return false;
    }
//生成随机码
    private function createRandStr($length)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $randStr = '';
        for ($i = 0; $length > $i; $i++) {
            $randStr .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $randStr;
    }
////查询收货地址
//    public function address(){
//        //收货地址查询
//            $id = input('id/d');
//            $list = AddressModel::order('id','desc')->select($id);
//            $this->success('收货地址查询',$list);
//    }
//添加收货地址
//    public function addAddress(){
//        //接收
//        $data=input('post.');
//        $ar = AddressModel::find($data['id']);
//        $ar->name=$data['name'];
//        $ar->mobile=$data['mobile'];
//        $ar->area=$data['area'];
//        $ar->address=$data['address'];
//        if($ar->save()){
//            $this->success('保存成功',[
//                'msg'=>$data,
//            ]);
//        }else{
//            $this->error('保存失败');
//        }
//    }
//收货地址查询
//查询
    public function address(\think\Request $request)
    {
        $user = AddressModel::field('name,mobile,area,address,user_id')->where('user_id',$request->userId)->select();
        $this-> success('查询成功',$user);
    }
//收货地址添加
    public function addAddress(\think\Request $request)
    {
        $date = input('post.');
        //验证数据
        $validate = new AddressValidate();
        $result = $validate->scene('add')->check($date);
        if (!$result) {
            $this->error($validate->getError());
        }
        $user = AddressModel::where('address',$date['address'])->find();
        if(!$user){
            $this->error('该地址已经存在');
        }
        $date['user_id'] = $request->userId;
        if (AddressModel::create($date)){
            $this-> success('添加地址成功');
        }else{
            $this-> error('添加地址失败');
        }
    }
//收货地址修改
    public function UpdateAddress(Request $request)
    {
        $date = input('post.');
        //验证数据
        $validate = new AddressValidate();
        $result = $validate->scene('edit')->check($date);
        if (!$result) {
            $this-> error($validate->getError());
        }
        $user = AddressModel::where('id',$date['id'])->find();
        if(!$user){
            $this-> error('该地址未拥有');
        }
        $user->mobile = $date['mobile'];
        $user->area = $date['area'];
        $user->name = $date['name'];
        $user->address = $date['address'];
        $user->user_id = $date['user_id'];
        if ($user->save()){
            $this-> success('修改成功',$user);
        }else{
            $this-> error('修改失败');
        }
    }
    public function DeleteAddress($id)
    {
        $news = AddressModel::find($id);
        if (!$news) {
            $this->error('地址不存在');
        }

        if ($news->delete()) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}